﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Marbles.Core.Content.Profiles;
using Marbles.Core.Content.Users;

namespace Marbles.Web.Admin.Content
{
    public partial class Profiles : ContentBase
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            string value = Request.Form["__USERID"];

            if (!string.IsNullOrEmpty(value))
            {
                ProfileResponseCollection item = new ProfileResponseCollection(this.CurrentWeb.SiteId, value);
                GenerateForm(item);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void LoadData()
        {
            User currentUser = User.GetCurrent();
            UserCollection items = new UserCollection(this.CurrentWeb.SiteId, !currentUser.Groups.Contains(4));
            cGrdUsers.DataSource = items;
            cGrdUsers.DataBind();
        }

        protected void Page_Command(object sender, CommandEventArgs e)
        {
            ProfileResponseCollection item = null;

            switch (e.CommandName)
            {
                case "Modify":
                    bool IsRoot = Page.AuthenticationProvider.CurrentToken.IsRoot;
                    cBtnSave.Enabled = IsRoot;
                    cBtnDelete.Enabled = IsRoot;
                    item = new ProfileResponseCollection(this.CurrentWeb.SiteId, e.CommandArgument.ToString());
                    cLtUserId.Text = "<input type=\"hidden\" id=\"__USERID\" name=\"__USERID\" value=\"" + e.CommandArgument.ToString() + "\" />";
                    GenerateForm(item);
                    cDlgProfile.Visible = true;
                    cBtnSave.CommandArgument = e.CommandArgument.ToString();
                    cBtnCancel.CommandArgument = e.CommandArgument.ToString();
                    break;
                case "Save":
                    item = new ProfileResponseCollection(this.CurrentWeb.SiteId, e.CommandArgument.ToString());
                    UpdateForm(this.cTblForm, item);
                    item.Update();
                    cBtnSave.CommandArgument = string.Empty;
                    cBtnCancel.CommandArgument = string.Empty;
                    cDlgProfile.Visible = false;
                    cLtUserId.Text = "";
                    LoadData();
                    break;
                case "Cancel":
                    item = new ProfileResponseCollection(this.CurrentWeb.SiteId, e.CommandArgument.ToString());
                    cBtnSave.CommandArgument = string.Empty;
                    cBtnCancel.CommandArgument = string.Empty;
                    cDlgProfile.Visible = false;
                    cLtUserId.Text = "";
                    LoadData();
                    break;
                case "Delete":
                    item = new ProfileResponseCollection(this.CurrentWeb.SiteId, e.CommandArgument.ToString());
                    item.Delete();
                    cBtnSave.CommandArgument = string.Empty;
                    cBtnCancel.CommandArgument = string.Empty;
                    cDlgProfile.Visible = false;
                    cLtUserId.Text = "";
                    LoadData();
                    break;
            }
        }


        private void UpdateForm(WebControl Parent, ProfileResponseCollection items)
        {
            int rowindex = 0;
            foreach (ProfileResponse item in items)
            {
                switch (item.Question.QuestionType)
                {
                    case ProfileQuestionType.Date:
                        TextBox ctxtDate = Parent.FindControl("Question" + item.Question.QuestionId.ToString()) as TextBox;
                        DateTime datevalue = Marbles.Core.Connectors.DataConnection.MinimumDateTime;
                        if (!DateTime.TryParse(ctxtDate.Text.Trim(), out datevalue)) { datevalue = Marbles.Core.Connectors.DataConnection.MinimumDateTime; }
                        item.Response = datevalue.ToString("dd/MM/yyyy");
                        break;
                    case ProfileQuestionType.Text:
                        TextBox txtSingleLine = Parent.FindControl("Question" + item.Question.QuestionId.ToString()) as TextBox;
                        item.Response = txtSingleLine.Text.Trim();
                        break;
                    case ProfileQuestionType.TextMulti:
                        TextBox txtMultiLine = Parent.FindControl("Question" + item.Question.QuestionId.ToString()) as TextBox;
                        item.Response = txtMultiLine.Text.Trim();
                        break;
                    case ProfileQuestionType.Year:
                        DropDownList drpYear = Parent.FindControl("Question" + item.Question.QuestionId.ToString()) as DropDownList;
                        item.Response = drpYear.SelectedValue;
                        break;
                    case ProfileQuestionType.YesNo:
                        DropDownList drpyesNo = Parent.FindControl("Question" + item.Question.QuestionId.ToString()) as DropDownList;
                        item.Response = drpyesNo.SelectedValue.ToLower();
                        break;
                    case ProfileQuestionType.ImageUpload:
                        FileUpload txtUpload = Parent.FindControl("Question" + item.Question.QuestionId.ToString()) as FileUpload;
                        if (txtUpload.HasFile)
                        {
                            string dir = HttpContext.Current.Server.MapPath("/App_Data/Profiles/" + items.UserId);
                            string extn = System.IO.Path.GetExtension(txtUpload.FileName);
                            if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); }

                            foreach (string file in System.IO.Directory.GetFiles(dir, items.UserId + ".*"))
                            {
                                System.IO.File.Delete(file);
                            }

                            dir = System.IO.Path.Combine(dir, items.UserId + extn);
                            txtUpload.SaveAs(dir);
                            item.Response = "/App_Data/Profiles/" + items.UserId;
                        }
                        break;
                    case ProfileQuestionType.YesNoChk:
                        CheckBox ChkyesNo = Parent.FindControl("Question" + item.Question.QuestionId.ToString()) as CheckBox;
                        item.Response = ChkyesNo.Checked.ToString().ToLower();
                        break;
                }

                rowindex += 1;
            }
        }

        private void GenerateForm(ProfileResponseCollection items)
        {
            bool IsRoot = Page.AuthenticationProvider.CurrentToken.IsRoot;
            int rowindex = 0;
            foreach (ProfileResponse item in items)
            {
                TableRow row = new TableRow();
                TableCell cellQuestion = new TableCell();
                TableCell blankCell = new TableCell();
                TableCell cellAnswer = new TableCell();
                blankCell.Text = "&nbsp;";
                row.ID = "row_" + rowindex.ToString();
                cellQuestion.ID = "cell_" + rowindex.ToString() + "_1";
                blankCell.ID = "cell_" + rowindex.ToString() + "_2";
                cellAnswer.ID = "cell_" + rowindex.ToString() + "_3";
                cellQuestion.VerticalAlign = VerticalAlign.Top;
                cellAnswer.VerticalAlign = VerticalAlign.Top;
                cellQuestion.Text = item.Question.Description;

                switch (item.Question.QuestionType)
                {
                    case ProfileQuestionType.Date:
                        DateTime dateValue = new DateTime(1980, 1, 1, 0, 0, 0);
                        TextBox ctxtDate = new TextBox();
                        ctxtDate.Enabled = IsRoot;
                        ctxtDate.ID = "Question" + item.Question.QuestionId.ToString();
                        ctxtDate.MaxLength = 10;
                        ctxtDate.Width = new Unit(100, UnitType.Pixel);
                        ctxtDate.Text = "";
                        if (DateTime.TryParse(item.Response, out dateValue))
                        {
                            ctxtDate.Text = dateValue.ToString("dd/MM/yyyy");
                        }
                        cellAnswer.Controls.Add(ctxtDate);
                        break;
                    case ProfileQuestionType.Text:
                        TextBox txtSingleLine = new TextBox();
                        txtSingleLine.Enabled = IsRoot;
                        txtSingleLine.ID = "Question" + item.Question.QuestionId.ToString();
                        txtSingleLine.Width = new Unit(300, UnitType.Pixel);
                        txtSingleLine.TextMode = TextBoxMode.SingleLine;
                        txtSingleLine.Text = item.Response;
                        cellAnswer.Controls.Add(txtSingleLine);
                        break;
                    case ProfileQuestionType.TextMulti:
                        TextBox txtMultiLine = new TextBox();
                        txtMultiLine.Enabled = IsRoot;
                        txtMultiLine.ID = "Question" + item.Question.QuestionId.ToString();
                        txtMultiLine.Width = new Unit(300, UnitType.Pixel);
                        txtMultiLine.Height = new Unit(40, UnitType.Pixel);
                        txtMultiLine.TextMode = TextBoxMode.MultiLine;
                        txtMultiLine.Text = item.Response;
                        cellAnswer.Controls.Add(txtMultiLine);
                        break;
                    case ProfileQuestionType.Year:
                        DropDownList drpYear = new DropDownList();
                        drpYear.Enabled = IsRoot;
                        drpYear.ID = "Question" + item.Question.QuestionId.ToString();
                        drpYear.Items.Add(new ListItem("", ""));
                        for (int i = 1900; i <= DateTime.Now.Year; i++)
                        {
                            drpYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                        }
                        drpYear.SelectedValue = item.Response;
                        cellAnswer.Controls.Add(drpYear);
                        break;
                    case ProfileQuestionType.ImageUpload:
                        FileUpload ctlUpload = new FileUpload();
                        ctlUpload.Enabled = IsRoot;
                        ctlUpload.ID = "Question" + item.Question.QuestionId.ToString();
                        cellAnswer.Controls.Add(ctlUpload);
                        break;
                    case ProfileQuestionType.YesNo:
                        DropDownList drpyesNo = new DropDownList();
                        drpyesNo.Enabled = IsRoot;
                        drpyesNo.ID = "Question" + item.Question.QuestionId.ToString();
                        drpyesNo.Items.Add(new ListItem("", ""));
                        drpyesNo.Items.Add(new ListItem("No", "false"));
                        drpyesNo.Items.Add(new ListItem("Yes", "true"));
                        drpyesNo.SelectedValue = item.Response;
                        cellAnswer.Controls.Add(drpyesNo);
                        break;
                    case ProfileQuestionType.YesNoChk:
                        CheckBox ChkyesNo = new CheckBox();
                        ChkyesNo.Enabled = IsRoot;
                        ChkyesNo.ID = "Question" + item.Question.QuestionId.ToString();
                        bool chkValue = false;
                        if (!bool.TryParse(item.Response.ToLower(), out chkValue)) { chkValue = false; }
                        ChkyesNo.Checked = chkValue;
                        cellAnswer.Controls.Add(ChkyesNo);
                        break;
                }

                row.Cells.Add(cellQuestion);
                row.Cells.Add(blankCell);
                row.Cells.Add(cellAnswer);
                cTblForm.Rows.Add(row);
                rowindex += 1;
            }

        }
    }
}